package com.ECPDemo.order.controller;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import com.ECPDemo.pojo.ECPResult;
import com.ECPDemo.pojo.Item;
import com.ECPDemo.pojo.Order;
import com.ECPDemo.pojo.OrderInfo;
import com.ECPDemo.pojo.WebItem;
import com.ECPDemo.service.OrderService;
import com.juefeng.common.utils.CookieUtils;
import com.juefeng.common.utils.JsonUtils;


@Controller
@RequestMapping("/order")
public class OrderController {

	Log log = LogFactory.getLog(OrderController.class);
	@Resource
	private OrderService orderService; 
	
	@RequestMapping("/order-cart")
	public String showOrderCart(HttpServletRequest request,HttpServletResponse response) {
		//从cookie中取商品列表
		String json = CookieUtils.getCookieValue(request, "CART_KEY", true);
		if (StringUtils.isNotBlank(json)) {
			//如果不为空转换成商品列表
			List<Item> list = JsonUtils.jsonToList(json, Item.class);
			List<WebItem> webItemList = new ArrayList<WebItem>();
			for (Item item : list) {
				webItemList.add(new WebItem(item));
			}
			//传递给订单确认页面
			request.setAttribute("cartList", webItemList);
		}
		return "order-cart";
	}
	

	@RequestMapping("/create")
	public String createOrder(Model model, OrderInfo orderInfo,HttpServletRequest request,HttpServletResponse response) {
		log.info("createOrder -----> " + orderInfo.toString());
		ECPResult result = orderService.createOrder(orderInfo.getOrderItems(), orderInfo.getOrderShipping(),orderInfo.getPayment());
		model.addAttribute("orderId", result.getData());
		model.addAttribute("payment", orderInfo.getPayment());
		Date date = new Date(System.currentTimeMillis() + (24 * 60 * 60 * 3));
		SimpleDateFormat format = new SimpleDateFormat("yyyy年-MM月-dd日"); 
		model.addAttribute("date", format.format(date));
		CookieUtils.setCookie(request, response, "CART_KEY", JsonUtils.objectToJson(new ArrayList<Item>()), 0, true);
		return "success";
	}
	
	@RequestMapping("/OrderList")
	public String showOrderList(Model model) {
		List<OrderInfo> orderList = orderService.getOrderList(new Order(null, null, 1L),1,20);
		
		log.info("showOrderList -----> orderList : " + orderList.toString());
		model.addAttribute("orderInfoList", orderList);
		return "my-orders";
	}
}
	